<template>
  <div class="search-container">
    <van-nav-bar
      :title="`${$route.query.keyword}的搜索结果`"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
      fixed
      palaceholder
    />

    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      class="search-list"
    >
      <van-cell
        v-for="(item, index) in showLight"
        :key="index"
        @click="
          $router.push({ path: '/article', query: { id: list[index].art_id } })
        "
      >
        <template #title>
          <div v-html="item"></div>
        </template>
      </van-cell>
    </van-list>
  </div>
</template>

<script>
import { getSearch } from './home.js'
export default {
  name: 'searchResult',
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1
    }
  },
  methods: {
    async onLoad () {
      // 异步更新数据
      let res = await getSearch({
        page: this.page,
        per_page: 10,
        q: this.$route.query.keyword
      })
      // console.log(res)

      // 上一页加载完毕，往list数组里面持续添加数据
      this.page++
      this.list.push(...res.data.data.results)

      // 加载状态结束
      this.loading = false

      // 数据全部加载完成
      if (res.data.data.results.length == 0) {
        this.finished = true
      }
    }
  },
  computed: {
    showLight () {
      let reg = new RegExp(this.$route.query.keyword, 'gi')
      return this.list.map(value => {
        return value.title.replace(reg, match => {
          return `<span style="color:red">${match}</span>`
        })
      })
    }
  }
}
</script>

<style lang="less">
.search-container {
  height: 100vh;
  padding-top: 46px;
  box-sizing: border-box;

  .search-list {
    height: 100%;
    overflow-y: auto;
  }
}
</style>
